package com.yiwei.jmx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.star.lockpattern.util.LockPatternUtil;
import com.star.lockpattern.widget.LockPatternView;
import com.yiwei.jmx.R;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.util.ACache;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.EnableScrollView;
import com.yiwei.jmx.view.V19FrameLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Sym on 2015/12/24.
 */
public class GestureLoginActivity extends BaseActivity {

    private static final String TAG = "LoginGestureActivity";

    @BindView(R.id.lockPatternView)
    LockPatternView lockPatternView;
    @BindView(R.id.messageTv)
    TextView messageTv;
    @BindView(R.id.btn_forget)
    TextView btnForget;

    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.txt_username)
    TextView txtUsername;
    @BindView(R.id.btn_change_account)
    TextView btnChangeAccount;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.scrollView)
    EnableScrollView scrollView;
    private int errorNum = 0;
    private ACache aCache;
    private static final long DELAYTIME = 600l;
    private byte[] gesturePassword;
    private Unbinder unbinder;
    private boolean is_check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_login);
        initBar();
        unbinder = ButterKnife.bind(this);
        this.init();
    }

    private void init() {
        txtTitle.setText("欢迎回来");
        is_check = getIntent().getBooleanExtra("is_check", false);
        setIsNeedCheckLogout(false);
        Glide.with(this).load(UserInfoGlobal.getHeader()).dontAnimate().placeholder(R.mipmap.img_guesture_default_icon).error(R.mipmap.img_guesture_default_icon).into(imgIcon);
        if (UserInfoGlobal.getIsOpenGuestureRoot()) {
            lockPatternView.setDrawLine(true);
        } else {
            lockPatternView.setDrawLine(false);
        }
        txtUsername.setText(UserInfoGlobal.getUserNick());
        aCache = ACache.get(GestureLoginActivity.this);
        //得到当前用户的手势密码
//        通过修改不同的key，有很多个手势密码
        gesturePassword = aCache.getAsBinary(Const.GESTURE_PASSWORD);
        lockPatternView.setOnPatternListener(patternListener);
        updateStatus(Status.DEFAULT);
    }

    private LockPatternView.OnPatternListener patternListener = new LockPatternView.OnPatternListener() {

        @Override
        public void onPatternStart() {
            scrollView.setSetTouchMode(false);
            lockPatternView.removePostClearPatternRunnable();
        }

        @Override
        public void onPatternComplete(List<LockPatternView.Cell> pattern) {
            scrollView.setSetTouchMode(true);
            if (pattern != null) {
                if (LockPatternUtil.checkPattern(pattern, gesturePassword)) {
                    updateStatus(Status.CORRECT);
//                    Util.startActivity(GestureLoginActivity.this, MainActivityNew.class);
                    UserInfoGlobal.saveGoLogoutTime();
                    if (is_check) {
                        Intent intent = new Intent(GestureLoginActivity.this, CreateGestureActivity.class);
                        intent.putExtra("is_check", true);
                        startActivity(intent);
                        finish();
                        overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    } else {
                        finish();
                    }

                } else {
                    errorNum++;
                    updateStatus(Status.ERROR);
                    if (errorNum >= 5) {
                        showErrorDialog();
                    }
                }
            }
        }
    };


    /**
     * 更新状态
     *
     * @param status
     */
    private void updateStatus(Status status) {
        if (is_check && status == Status.DEFAULT) {
            messageTv.setText("请绘制原手势密码");
        } else {
            messageTv.setText(status.strId);
        }
        messageTv.setTextColor(getResources().getColor(status.colorId));
        switch (status) {
            case DEFAULT:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                break;
            case ERROR:
                lockPatternView.setPattern(LockPatternView.DisplayMode.ERROR);
                lockPatternView.postClearPatternRunnable(DELAYTIME);
                break;
            case CORRECT:
                lockPatternView.setPattern(LockPatternView.DisplayMode.DEFAULT);
                loginGestureSuccess();
                break;
        }
    }

    private void showErrorDialog() {
        Dialog.showDefaultDialog(this, "提示", "很抱歉，您已经绘制手势密码五次错误了，是否确定重新登录？", "取消", "重新登录", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                Util.startActivity(GestureLoginActivity.this, LoginTotalActivity.class);
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    private void showForgetDialog() {
        Dialog.showDefaultDialog(this, "提示", "是否删除已有手势密码，使用登录密码重新登录？", "取消", "重新登录", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                UserInfoGlobal.setIsOpenGuesture(false);
                aCache.clear();
                UserInfoGlobal.logout();
                Util.startActivity(GestureLoginActivity.this, LoginTotalActivity.class);
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    private void showAccountDialog() {
        Dialog.showDefaultDialog(this, "提示", "确认退出当前账号，使用其他账号登录？", "取消", "更换账号", false, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                UserInfoGlobal.logout();
                Util.startActivity(GestureLoginActivity.this, LoginTotalActivity.class);
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    /**
     * 手势登录成功（去首页）
     */
    private void loginGestureSuccess() {
        ToastUtil.makeText(this, "验证成功");
//        Toast.makeText(GestureLoginActivity.this, "success", Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.btn_back, R.id.btn_wechat, R.id.btn_forget, R.id.btn_change_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                if (is_check) {
                    finish();
                } else {
                    UserInfoGlobal.logout();
                    Util.startActivity(GestureLoginActivity.this, LoginTotalActivity.class);
                    finish();
                }

                break;
            case R.id.btn_wechat:
                Util.startActivity(this, WechatChatActivity.class);
                break;
            case R.id.btn_forget:
                showForgetDialog();
                break;
            case R.id.btn_change_account:
                showAccountDialog();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (is_check) {
            finish();
        } else {
            UserInfoGlobal.logout();
            Util.startActivity(GestureLoginActivity.this, LoginTotalActivity.class);
            finish();
        }

    }

    private enum Status {
        //默认的状态
        DEFAULT(R.string.gesture_default, R.color.main_color),
        //密码输入错误
        ERROR(R.string.gesture_error, R.color.red_f4333c),
        //密码输入正确
        CORRECT(R.string.gesture_correct, R.color.main_color);

        private Status(int strId, int colorId) {
            this.strId = strId;
            this.colorId = colorId;
        }

        private int strId;
        private int colorId;
    }

    @Override
    protected void onDestroy() {
        patternListener = null;
        lockPatternView.removePostClearPatternRunnable();
        lockPatternView.setOnPatternListener(null);
        unbinder.unbind();
        unbinder = null;
        super.onDestroy();

    }

}
